#!/usr/bin/env python
# -*- coding:utf-8 -*-
from django import forms
from django.urls import reverse
from django.utils.safestring import mark_safe
from django.http import QueryDict

from stark.service.stark import StarkConfig, get_date_text, Option
from stark.forms.widgets import DatePickerInput
from stark.forms.forms import StarkModelForm
from stark.utils.convert import model_to_dict
from teach import models


class ClassModelForm(StarkModelForm):
    class Meta:
        model = models.Class
        fields = '__all__'
        widgets = {
            'start_date': DatePickerInput(attrs={'class': 'date-picker '})
        }


class ClassHandler(StarkConfig):
    """
    班级管理
    """

    def display_daily(self, row=None, header=False):
        if header:
            return '讲课大纲'
        url = reverse("stark:teach_teachingdaily_changelist", kwargs={'cls_id': row.pk, 'course_id': row.course_id})

        return mark_safe('<a href="%s">讲课大纲</a>' % url)

    list_display = ['course', 'num', get_date_text('start_date', '开班时间'), display_daily]

    model_form_class = ClassModelForm

    list_filter = [
        Option('course')
    ]

    order_by = ['-id']

    def save(self, form, modify=False):
        """
        创建或编辑班级
        :param form:
        :param modify:
        :return:
        """
        # 1. 保存班级信息
        class_object = form.save()

        # 2. 创建班级：为班级创建课程大纲
        if not modify:
            outline_daily_list = models.Daily.objects.filter(module__course=form.instance.course)
            for row in outline_daily_list:

                info = model_to_dict(row, exclude=['id'])
                info['cls'] = class_object
                models.TeachingDaily.objects.create(**info)
